package com.ruoyi.rsikManage.service.Impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.GenericMethods;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.StreamProtocol;
import com.ruoyi.rsikManage.domain.JyDemoJsonStr;
import com.ruoyi.rsikManage.domain.TUnitConfig;
import com.ruoyi.rsikManage.domain.common.SubscriptionsRequest;
import com.ruoyi.rsikManage.domain.vo.DiagnosisPlanRequestBody;
import com.ruoyi.rsikManage.mapper.VideoRtspMapper;
import com.ruoyi.rsikManage.service.JyService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.servlet.ServletContext;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class JyServiceImpl implements JyService {
    @Value("${jy.ip}")
    private String JY_IP;
    @Value("${jy.switch}")
    private boolean JY_SWITCH;

    @Value("${jy.local_ip}")
    private String JY_LOCALHOST_IP;

    @Value("${jy.client_id}")
    private String client_id;

    @Value("${jy.client_secret}")
    private String client_secret;

    @Value("${jy.request_prefix}")
    private String Request_Prefix;

    @Autowired
    private ServletContext servletContext;



    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    //请求参数
    String grant_type = "client_credentials";

    String format = "json";
    //对象头中的请求参数
    String user = "usercode:YGSJ";
    String cookie = "usercode=YGSJ";
    String contentType = "application/json";


    @Autowired
    private VideoRtspMapper videoRtspMapper;

    /**
     * 设置请求头参数
     */
    public void setHeaders() {
        //从容器中获取 access_token
        headers.set("Authorization",(String) servletContext.getAttribute("access_token"));
        headers.set("User", user);
        headers.set("Cookie", cookie);
        headers.set("Content-Type", contentType);
    }

    /**
     * 设置请求头参数
     */
    public void setHeadersForUnitCodes(TUnitConfig tUnitConfig,HttpHeaders headers) {
        Long unitCode = tUnitConfig.getUnitCode();
        //从容器中获取 access_token
        headers.set("Authorization",(String) servletContext.getAttribute(unitCode+"_"+"access_token"));
        String jyClientId = tUnitConfig.getJyClientId();
        user= "usercode:"+jyClientId;
        cookie="usercode="+jyClientId;
        headers.set("User", user);
        headers.set("Cookie", cookie);
        headers.set("Content-Type", contentType);
    }
    @Override
    public HttpHeaders getHttpHeader() {
        setHeaders();
        return headers;
    }
    @Override
    public AjaxResult getPasswordFreeLoginURL(RestTemplate restTemplate)
        {
        /*
        步骤一 获取TGT（登录票据：有效期8小时）
         */
            // 设置请求头信息
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

            // 构造请求体（参数）
            MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
            body.add("username", "YGSJ");
            body.add("password", "04FA4605FC5A707EBFFACC824486ED95");
            String url="http://"+JY_IP+":11125/sso/v1/tickets";
            // 构造请求对象
            HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(body, headers);

            // 发送POST请求并获取响应
            ResponseEntity<String> response = restTemplate.postForEntity(url, httpEntity, String.class);

            // 获取响应体中的TGT
            String tgt = response.getBody();

        /*
        步骤二  获取ST（服务票据：有效期一分钟）
         */
            // 构造请求体（参数）
            MultiValueMap<String, String> body2 = new LinkedMultiValueMap<>();
            body2.add("service", "http://"+JY_IP+":9000/cas/validate");
            // 构造请求对象
            HttpEntity<MultiValueMap<String, String>> httpEntity2 = new HttpEntity<>(body2, headers);
            // 发送POST请求并获取响应
            ResponseEntity<String> response2 = restTemplate.postForEntity(url+"/"+tgt, httpEntity2, String.class);

            // 获取响应体中的TGT
            String st = response2.getBody();

            // 处理TGT并返回相应结果
            System.out.println(tgt);
            System.out.println(st);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", "http://"+JY_IP+":9000/cas/validate"+"?ticket="+st);
            ajax.put("code", 200);
            return ajax;
        }

    //免密登录 集团版
    @Override
    public AjaxResult getPasswordFreeLoginURLForUnitCodes(TUnitConfig tUnitConfig) {
        try {
            JY_IP = tUnitConfig.getJyIp();
            /*
            步骤一 获取TGT（登录票据：有效期8小时）
             */
            // 设置请求头信息
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

            // 对密码进行MD5加密
            String encryptedPassword = md5Encrypt(tUnitConfig.getJyClientSecret());

            // 构造请求体（参数）
            MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
            body.add("username", tUnitConfig.getJyClientId());
            body.add("password", encryptedPassword);
            String url = "http://" + JY_IP + ":11125/sso/v1/tickets";

            // 构造请求对象
            HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(body, headers);

            // 发送POST请求并获取响应
            ResponseEntity<String> response = restTemplate.postForEntity(url, httpEntity, String.class);

            // 获取响应体中的TGT
            String tgt = response.getBody();

            /*
            步骤二  获取ST（服务票据：有效期一分钟）
             */
            // 构造请求体（参数）
            MultiValueMap<String, String> body2 = new LinkedMultiValueMap<>();
            body2.add("service", "http://" + JY_IP + ":9000/cas/validate");

            // 构造请求对象
            HttpEntity<MultiValueMap<String, String>> httpEntity2 = new HttpEntity<>(body2, headers);
            // 发送POST请求并获取响应
            ResponseEntity<String> response2 = restTemplate.postForEntity(url + "/" + tgt, httpEntity2, String.class);

            // 获取响应体中的ST
            String st = response2.getBody();

            // 处理TGT和ST并返回相应结果
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", "http://" + JY_IP + ":9000/cas/validate?ticket=" + st);
            ajax.put("code", 200);
            return ajax;

        } catch (NoSuchAlgorithmException e) {
            // 处理异常情况
            e.printStackTrace();
            return AjaxResult.error("Error occurred during MD5 encryption.");
        }
    }

    private String md5Encrypt(String input) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] messageDigest = md.digest(input.getBytes());
        StringBuilder hexString = new StringBuilder();
        for (byte b : messageDigest) {
            String hex = Integer.toHexString(0xFF & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }

    @Override
    public String getAccessToken() {
        if (!JY_SWITCH) {
            return "{}";
        }
        String url = "http://"+JY_IP+":11125/sso/oauth2.0/accessToken?grant_type=" + grant_type + "&client_id=" + client_id+ "&client_secret=" + client_secret+ "&format=" + format;
        //发送get请求
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
        return responseEntity.getBody();
    }

    @Override
    public String getAccessTokenForUnitCodes(TUnitConfig tUnitConfig) {
        if (!JY_SWITCH) {
            return "{}";
        }
        JY_IP=tUnitConfig.getJyIp();
        client_id=tUnitConfig.getJyClientId();
        client_secret=tUnitConfig.getJyClientSecret();
        String url = "http://"+JY_IP+":11125/sso/oauth2.0/accessToken?grant_type=" + grant_type + "&client_id=" + client_id+ "&client_secret=" + client_secret+ "&format=" + format;
        //发送get请求
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
        return responseEntity.getBody();
    }

    @Override
    public String getNewAccessToken() {
        if (!JY_SWITCH) {
            return "{}";
        }
        //从容器中获取 refresh_token
        String refresh_token = servletContext.getAttribute("refresh_token").toString();
        String url = "http://"+JY_IP+":11125/sso/oauth2.0/accessToken?grant_type="+ grant_type+ "&client_id=" + client_id+ "&client_secret=" + client_secret +"&format=" + format + "&refresh_token=" + refresh_token;
        //发送get请求
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
        return responseEntity.getBody();
    }

    @Override
    public String getNewAccessTokenForUnitCodes(TUnitConfig tUnitConfig) {
        if (!JY_SWITCH) {
            return "{}";
        }
        JY_IP=tUnitConfig.getJyIp();
        client_id=tUnitConfig.getJyClientId();
        client_secret=tUnitConfig.getJyClientSecret();
        Long unitCode = tUnitConfig.getUnitCode();
        //从容器中获取 refresh_token
        String refresh_token = servletContext.getAttribute(unitCode+"_"+"refresh_token").toString();
        String url = "http://"+JY_IP+":11125/sso/oauth2.0/accessToken?grant_type="+ grant_type+ "&client_id=" + client_id+ "&client_secret=" + client_secret +"&format=" + format + "&refresh_token=" + refresh_token;
        //发送get请求
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
        return responseEntity.getBody();
    }

    @Override
    public String eventSubscriptions(Map<String,Object> param) {
        //设置请求头
        setHeaders();
        //构造请求体（参数）
        Map<String, Object> body = new HashMap<>();
        body.put("mode", param.get("mode"));
        body.put("event_type_list", param.get("event_type_list"));
        body.put("accept_url", param.get("accept_url"));
        //构造请求对象
        HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(body, headers);
        String url = "http://"+JY_IP+":11125/api/eco/v2/evc/event/subscriptions";
        //发送POST请求
        ResponseEntity<String> response = restTemplate.postForEntity(url, httpEntity, String.class);
        return response.getBody();
    }

    /**
     * 创建或更新指定单位代码的事件订阅
     *
     * @param tUnitConfig 单位配置对象
     * @param  param 订阅请求对象，包含接受 URL、模式和事件类型列表
     * @return 创建或更新操作的结果字符串
     */
    @Override
    public String eventSubscriptionsForUnitCodes(TUnitConfig tUnitConfig, Map<String,Object> param) {
        try {

            // 初始化请求头
            HttpHeaders headers = new HttpHeaders();
            setHeadersForUnitCodes(tUnitConfig, headers);

            // 获取 JY_IP 地址
            String JY_IP = tUnitConfig.getJyIp();

            // 构造请求体（参数）
            Map<String, Object> body = new HashMap<>();
            body.put("mode", param.get("mode"));
            body.put("event_type_list", param.get("event_type_list"));
            body.put("accept_url", param.get("accept_url"));

            // 构造请求对象
            HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(body, headers);

            // 构造请求 URL
            String url = "http://" + JY_IP + ":11125/api/eco/v2/evc/event/subscriptions";

            // 发送 POST 请求
            ResponseEntity<String> response = restTemplate.postForEntity(url, httpEntity, String.class);

            // 检查响应状态码
            if (response.getStatusCode().is2xxSuccessful()) {
                return response.getBody();
            } else {
                return "Failed to create or update event subscriptions. Status code: " + response.getStatusCodeValue();
            }
        } catch (Exception e) {
            throw new RuntimeException("Error creating or updating event subscriptions", e);
        }
    }

    @Override
    public String selectEventSubscriptions() {

        //设置请求头
        setHeaders();
        // 构造请求对象
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
        String url = "http://"+JY_IP+":11125/api/eco/v2/evc/event/subscriptions";
        //发送get请求
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
        return exchange.getBody();
    }
    /**
     * 查询指定单位代码的事件订阅
     *
     * @param tUnitConfig 单位配置对象，包含单位代码和其他相关信息
     * @return 查询结果的字符串，如果查询成功则返回事件订阅信息，否则返回错误信息
     */
    @Override
    public String selectEventSubscriptionsForUnitCodes(TUnitConfig tUnitConfig) {
        try {
            // 初始化请求头
            HttpHeaders headers = new HttpHeaders();
            setHeadersForUnitCodes(tUnitConfig, headers);

            // 获取 JY_IP 地址
            String JY_IP = tUnitConfig.getJyIp();

            // 构造请求对象
            HttpEntity<Object> httpEntity = new HttpEntity<>(headers);

            // 构造请求 URL
            String url = "http://" + JY_IP + ":11125/api/eco/v2/evc/event/subscriptions";

            // 发送 GET 请求
            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);

            // 检查响应状态码
            if (response.getStatusCode().is2xxSuccessful()) {
                return response.getBody();
            } else {
                return "Failed to select event subscriptions. Status code: " + response.getStatusCodeValue();
            }
        } catch (Exception e) {
            throw new RuntimeException("Error selecting event subscriptions", e);
        }
    }

    @Override
    public String deleteEventSubscriptions(Map<String, Object> param) {

        //设置请求头
        setHeaders();
        // 构造请求体（参数）
        Map<String, Object> body = new HashMap<>();
        body.put("event_type_list", param.get("event_type_list"));
        // 构造请求对象
        HttpEntity httpEntity = new HttpEntity(body, headers);
        String url = "http://"+JY_IP+":11125/api/eco/v2/evc/event/subscriptions";

        //发送delete请求
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.DELETE, httpEntity, String.class);
        return exchange.getBody();
    }

    /**
     * 删除指定单位代码的事件订阅
     *
     * @param tUnitConfig 单位配置对象，包含单位代码、IP地址等信息
     * @param param 订阅请求对象，包含要删除的事件类型列表
     * @return 删除操作的结果字符串，如果删除成功则返回成功信息，否则返回错误信息
     */
    @Override
    public String deleteEventSubscriptionsForUnitCodes(TUnitConfig tUnitConfig,Map<String, Object> param) {
        try {

            // 初始化请求头
            HttpHeaders headers = new HttpHeaders();
            setHeadersForUnitCodes(tUnitConfig, headers);

            // 获取 JY_IP 地址
            String JY_IP = tUnitConfig.getJyIp();

            // 构造请求体（参数）
            Map<String, Object> body = new HashMap<>();
            body.put("event_type_list", param.get("event_type_list"));

            // 构造请求对象
            HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(body, headers);

            // 构造请求 URL
            String url = "http://" + JY_IP + ":11125/api/eco/v2/evc/event/subscriptions";

            // 发送 DELETE 请求
            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.DELETE, httpEntity, String.class);

            // 检查响应状态码
            if (response.getStatusCode().is2xxSuccessful()) {
                return response.getBody();
            } else {
                return "Failed to delete event subscriptions. Status code: " + response.getStatusCodeValue();
            }
        } catch (Exception e) {
            throw new RuntimeException("Error deleting event subscriptions", e);
        }
    }

    @Override
    public String picAddrTrans(List<String> addrList) {
        //设置请求头
        setHeaders();
        // 构造请求对象
        HttpEntity httpEntity = new HttpEntity(addrList, headers);
        String url = "http://"+JY_IP+":11125/api/viid/v3/mda/addr-trans";
        //发送请求
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
        return exchange.getBody();
    }

    @Override
    public String picAddrTransForUnitCodes(List<String> addrList,TUnitConfig tUnitConfig) {

        // 初始化请求头
        HttpHeaders headers = new HttpHeaders();

        setHeadersForUnitCodes(tUnitConfig, headers);

        // 获取 JY_IP 地址
        String JY_IP = tUnitConfig.getJyIp();
        // 构造请求对象
        HttpEntity httpEntity = new HttpEntity(addrList, headers);
        String url = "http://"+JY_IP+":11125/api/viid/v3/mda/addr-trans";
        System.out.println("picAddrTransForUnitCodes"+url);
        //发送请求
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
        return exchange.getBody();
    }

    @Override
    public String getChannelListWithDevice() {
        if (!JY_SWITCH) {
            return JyDemoJsonStr.channelListWithDevice;
        }
        //设置请求头信息
        setHeaders();
        // 构造请求对象
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
        String url = "http://"+JY_IP+":11125/api/bss/v1/udm/channel/list-with-device?page_size=9999";
        //发送get请求
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
        return exchange.getBody();
    }

    @Override
    public String getChannelListWithDeviceForUnitCodes(TUnitConfig tUnitConfig) {
        if (!JY_SWITCH) {
            return JyDemoJsonStr.channelListWithDevice;
        }
        HttpHeaders headers = new HttpHeaders();
        //设置请求头信息
        setHeadersForUnitCodes(tUnitConfig,headers);
        // 构造请求对象
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
        JY_IP=tUnitConfig.getJyIp();
        String url = "http://"+JY_IP+":11125/api/bss/v1/udm/channel/list-with-device?page_size=9999";
        System.out.println(url);
        //发送get请求
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
        return exchange.getBody();
    }

    @Override
    public List<Map<String, Object>> getLiveStreamUrl(Map<String, Object> param) {
        setHeaders();
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
        List<Map<String, Object>> mapsRtsp = new ArrayList<>();
        List<Map> monitorPoints = videoRtspMapper.selectAllRtsp();
//        String channel_code = Optional.ofNullable(param.get("apeId")).orElse(null).toString();
        String channel_code = Optional.ofNullable(param.get("cameraIndexCode")).orElse(null).toString();
        String stream_type = Optional.ofNullable(param.get("stream_type")).orElse("0").toString();
        String stream_mode = Optional.ofNullable(param.get("stream_mode")).orElse("3").toString();
        String keep_alive = Optional.ofNullable(param.get("keep_alive")).orElse("99999").toString();
        String visit_ip = Optional.ofNullable(param.get("visit_ip")).orElse(JY_LOCALHOST_IP).toString();

            Map<String, Object> resultMap = new HashMap<>();
            try {
                String url = buildUrl(channel_code, stream_type, stream_mode, keep_alive, visit_ip);

                ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
                String body = exchange.getBody();

                Map<String, Object> responseMap = new ObjectMapper().readValue(body, Map.class);
                String rtspValue = responseMap.get("data").toString();

                resultMap.put("rtsp", rtspValue);
                resultMap.put("rtspUrl", rtspValue);

                resultMap.put("apeId", channel_code);

                mapsRtsp.add(resultMap);
            } catch (Exception e) {
                e.printStackTrace();
                resultMap.put("apeId", channel_code);
                resultMap.put("rtsp", null);
                resultMap.put("rtspUrl", null);

                mapsRtsp.add(resultMap);
            }
        return mapsRtsp;
    }

    private String buildUrl(String channel_code, String stream_type, String stream_mode, String keep_alive, String visit_ip) {
        return "http://" + JY_IP + ":11125/api/vms/v2/webuas/live/stream/url?channel_code=" +
                channel_code + "&stream_type=" + stream_type + "&stream_mode=" + stream_mode +
                "&keep_alive=" + keep_alive + "&visit_ip=" + visit_ip;
    }

    @Override
    public List<Map<String,Object>> getLiveStreamUrlApp(Map<String, Object> param) {
        // 设置请求头信息
        setHeaders();
        // 构造请求对象
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
        String visit_ip = (param.get("visitIp") == null || param.get("visitIp").toString().isEmpty()) ? JY_LOCALHOST_IP : param.get("visitIp").toString();
        String RequestPrefix = Optional.ofNullable(param.get("RequestPrefix")).orElse("http://124.70.90.158:9999/live/").toString();

//
        Map<String,Object> result= new HashMap<>();
        List<Map<String,Object>> mapsRtsp = new ArrayList<>();
        List<Map> monitorPoints =  videoRtspMapper.selectAllRtsp();
//        String apeIdValue =;

        Object apeIdObj = param.get("apeId");
        if (apeIdObj != null && !apeIdObj.toString().isEmpty()) {
            String apeId = apeIdObj.toString();
            List<Map> filteredList = monitorPoints.stream()
                    .filter(map -> map.get("apeId").toString().equals(apeId))
                    .collect(Collectors.toList());
            monitorPoints = filteredList;
        }

        for (Map apeId : monitorPoints) {
            Map<String,Object> resultMap= new HashMap<>();
            try {
                String channel_code = apeId.get("apeId").toString();

                String stream_type = "0";

                String stream_mode = "3";

                String keep_alive = "100";

                String url = "http://"+JY_IP+":11125/api/vms/v2/webuas/live/stream/url?channel_code="
                        + channel_code + "&stream_type=" + stream_type + "&stream_mode=" + stream_mode
                        +  "&keep_alive=" + keep_alive + "&visit_ip=" + visit_ip;
                // 发送get请求
                ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
                String body = exchange.getBody();

                ObjectMapper objectMapper = new ObjectMapper();
                Map<String, Object> responseMap = objectMapper.readValue(body, Map.class);

//              Map<String, Object> dataMap = (Map<String, Object>) responseMap.get("data");
//              String rtspValue = (String) dataMap.get("rtsp");
                String rtspValue =  responseMap.get("data").toString();
//                Field[] fields = apeId.getClass().getDeclaredFields();
//                for (Field field : fields) {
//                    field.setAccessible(true);
//                    String fieldName = field.getName();
//                    Object fieldValue = field.get(apeId);
//                    resultMap.put(fieldName, fieldValue.toString());
//                }
                resultMap.put("rtsp",rtspValue);
                resultMap.put("rtspUrl",rtspValue);
//              resultMap.put("apeData",apeId);
                resultMap.put("apeId",apeId.get("apeId").toString());
                resultMap.put("name",apeId.get("name").toString());
                resultMap.put("ownerApsIp",apeId.get("ownerApsIp").toString());
//
//                result.put("data",resultMap);
                mapsRtsp.add(resultMap);
//
                // 其他处理逻辑...

            } catch (Exception e) {
                // 处理异常，可以进行日志记录等操作
                e.printStackTrace();
//                resultMap.put("apeData",apeId);
                resultMap.put("apeId",apeId.get("apeId").toString());
                resultMap.put("name",apeId.get("name").toString());

                resultMap.put("rtsp","");
//                result.put("data",resultMap);
                mapsRtsp.add(resultMap);

                // 继续下一次循环
                continue;
            }
        }
        //

        return mapsRtsp;
    }
    /**
     * 获取直播流URL的方法，针对App版本2进行优化。
     * 参考文档 UNISINSIGHT 智能视觉管理平台REST API 接口手册 P7-139 7.3.1 视频预览-获取实况 URL
     *  /api/vms/v2/webuas/live/stream/url
     * @param param 请求参数Map，包含apeId(频道编码), stream_type(流类型), stream_mode(流模式), keep_alive(连接保活时间), visit_ip(访问IP)等
     * @return 包含直播流URL及响应状态的Map对象
     */
    @Override
    public Map<String, Object> getLiveStreamUrlAppV2(Map<String, Object> param) {
        //    1. 设置HTTP请求头信息，为调用极云接口做准备
        setHeaders();

        //    2. 创建HttpEntity对象，包含上面设置的请求头信息
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);

        //    3.channel_code 通道编码 （必填）
        String channel_code = Optional.ofNullable(param.get("apeId")).orElse(null).toString();

        //    stream_type:流类型，0：主码流，1：辅码流。建议使用主码流 （必填）
        String stream_type = Optional.ofNullable(param.get("stream_type")).orElse("0").toString();

        //  4.stream_mode:流协议，1：RTSP，2：RTMP，3：HLS，4：HLS_SSL 5.HTTP FLV 6.HTTPS FLV 7.WS FLV 8.WSS FLV
        //引入流协议枚举类StreamProtocol （必填）
        String stream_mode = Optional.ofNullable(param.get("stream_mode")).orElse(StreamProtocol.HLS.value).toString();

        //  7.keep_alive url有效时间(单位:秒)，默认10分钟有效时间 （必填）
        String keep_alive = Optional.ofNullable(param.get("keep_alive")).orElse("9999999").toString();

        //  8.访问IP，请求的目标IP，用于判断访问者所在的网域，默认为局域网访问 （必填）
        String visit_ip = Optional.ofNullable(param.get("visit_ip")).orElse(JY_LOCALHOST_IP).toString();

        //  5.0:HLS http-flv协议通过8060端口拉流(https为30443)，1:通过ingress40087端口拉流(https为40089)默认值0 (只对HLShttp-flv有效) （非必填）
        String port_type = Optional.ofNullable(param.get("port_type")).orElse(0).toString();

        //  6.h265_muxer_type HLS协议对于H265编码的视频的封装类型，0:fmp4封装，1:TS封装，默认0，（只对HLS协议并且当前码流是H265的时候有效）（非必填）
        String h265_muxer_type = Optional.ofNullable(param.get("h265_muxer_type")).orElse(0).toString();
        // 初始化结果和数据Map，用于存放响应信息
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> data = new HashMap<>();

        try {
            // 3. 根据参数构建目标URL
            String url = buildLiveUrl(channel_code, stream_type, stream_mode, keep_alive, visit_ip,port_type,h265_muxer_type);

            // 4. 使用RestTemplate发起GET请求，并获取响应实体
            ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
            String body = exchange.getBody();

            // 5. 将响应体JSON字符串转换为Map对象
            Map<String, Object> responseMap = new ObjectMapper().readValue(body, Map.class);
            // 从响应数据中提取视频流地址
            String StreamAddress = responseMap.get("data").toString();
            // 6. 填充响应数据到data Map中
            data.put("apeId", channel_code);
            data.put("streamAddress", StreamAddress);
            //获取对应的视频流类型
            data.put("streamMode", StreamProtocol.getDescriptionByValue(Integer.parseInt(stream_mode)));
            // 7. 组装最终响应结果
            result.put("data", data);
            result.put("code", 200);
            result.put("msg", "查询成功");

        } catch (Exception e) {
            // 处理请求过程中的任何异常
            e.printStackTrace();
            // 异常时的数据填充，rtsp设为null，保留apeId
            data.put("apeId", channel_code);
            data.put("StreamAddress", null);
            data.put("streamMode", null);
            // 设置异常响应状态和消息
            result.put("data", data);
            result.put("code", 500);
            result.put("msg", "查询异常");
        }

        // 返回最终的响应Map
        return result;
    }

    @Override
    public Map<String, Object> getLiveStreamUrlFinalAppV2(Map<String, Object> param) {
        Map<String, Object> liveStreamUrlMap = getLiveStreamUrlAppV2(param);
        Map<String,Object> map = new HashMap<>();
        String videoUrl="";
        String streamMode="";
        if (liveStreamUrlMap!=null){
            Object data = liveStreamUrlMap.get("data");
            Map<String, Object> dataMap = (Map<String, Object>) data;
            videoUrl = (String)dataMap.get("streamAddress");
            streamMode = (String)dataMap.get("streamMode");
        }
        try {
            //             创建URL对象
            URL url = new URL(videoUrl);
            // 创建HttpURLConnection对象
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 设置请求方法
            conn.setRequestMethod("GET");
            // 获取响应码
            int responseCode = conn.getResponseCode();
            System.out.println("Response Code : " + responseCode);
            // 读取响应内容
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            System.out.println("Response Content: " + response);
            map.put("url",response.toString());
            map.put("JSON", parse(response.toString()));
            System.out.println(parse(response.toString()));
            String hls = extractHLS(response.toString());
            String streamAddress = Request_Prefix+ "/live/"+hls+".m3u8";
            System.out.println("Extracted HLS: " + hls);
            List<String> strings =extractSegments(response.toString());
            List<String> results = new ArrayList<>();
            for (String str : strings) {
                String[] parts = str.split("/", 2); // 使用限制为2的split，将字符串分割为两部分
                if (parts.length > 0) {
                    results.add(parts[0]+".m3u8"); // 将分割后的第一部分添加到结果列表中
                }
            }
            List<String> modifiedStrings = new ArrayList<>();
            for (String str : results) {
                String modifiedStr = Request_Prefix+ "/live/" +str;
                modifiedStrings.add(modifiedStr);
            }

            map.put("strings",strings);
            map.put("modifiedStr",modifiedStrings);
            map.put("hls",results);
            map.put("streamAddress",streamAddress);
            map.put("streamMode",streamMode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }


    public String getLiveStreamUrlOfTheMonitor(String channel_code, String stream_type,String stream_mode, String keep_alive, String visit_ip) throws JsonProcessingException {
        // 设置请求头信息
        setHeaders();
        // 构造请求对象
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);

        String url = "http://"+JY_IP+":11125/api/vms/v2/webuas/live/stream/url?channel_code="
                + channel_code + "&stream_type=" + stream_type + "&stream_mode=" + stream_mode
                +  "&keep_alive=" + keep_alive + "&visit_ip=" + visit_ip;
        // 发送get请求
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);

        String body = exchange.getBody();
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Object> responseMap = objectMapper.readValue(body, Map.class);
        String rtspValue =  responseMap.get("data").toString();

        return rtspValue;
    }

    @Override
    public String getReplayStreamUrlOfTheMonitor(String channelCode, String startTime, String endTime, String streamMode) {
        // 设置请求头信息
        setHeaders();
        // 构造请求对象
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // 解析字符串时间为 LocalDateTime 对象
        LocalDateTime localStartDateTime = LocalDateTime.parse(startTime, formatter);
        LocalDateTime localEndDateTime = LocalDateTime.parse(endTime, formatter);
        ZoneId shanghaiZone = ZoneId.of("GMT+8");
        ZonedDateTime shanghaiStartDateTime = localStartDateTime.atZone(shanghaiZone);
        ZonedDateTime shanghaiEndDateTime = localEndDateTime.atZone(shanghaiZone);

        long startTimestamp = shanghaiStartDateTime.toInstant().getEpochSecond();
        long endTimestamp = shanghaiEndDateTime.toInstant().getEpochSecond();

        int start_time = (int) startTimestamp;
        int end_time = (int) endTimestamp;

        String url = "http://"+JY_IP+":11125/api/vms/v2/webuas/replay/stream/url?channel_code="
                + channelCode + "&start_time=" + start_time + "&end_time="+ end_time +"&stream_mode=" + streamMode
                + "&source_type=0";
        String resStr;
        //发送get请求
        try {
            SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
            requestFactory.setConnectTimeout(4000);
            requestFactory.setReadTimeout(5000);
            restTemplate.setRequestFactory(requestFactory);
            ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
            resStr = exchange.getBody();
        } catch (RestClientException e) {
            resStr = e.getMessage();
            throw new RuntimeException(e);
        }
//        JSONObject replayStreamUrlJsonObj = JSONObject.parseObject(exchange.getBody()).getJSONObject("data");
//            resStr = replayStreamUrlJsonObj.getString("url");
        return resStr;
    }


    /**
     * 获取直播流回放地址
     * @param param 参数列表，包括startTime, endTime, apeId等
     * @return 直播流回放地址列表
     */
    @Override
    public List<Map<String, Object>> getLiveStreamUrlReplay(Map<String, Object> param) {

        setHeaders(); // 设置请求头信息
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers); // 构造请求对象

        String channel_code = Optional.ofNullable(param.get("apeId")).orElse(null).toString();
        //source_type:录像文件源，0：平台录像，1：设备/级联录像
        String source_type = Optional.ofNullable(param.get("source_type")).orElse("1").toString();

        //stream_mode:流协议，1：RTSP，2：RTMP，3：HLS，4：HLS_SSL
        String stream_mode = Optional.ofNullable(param.get("stream_mode")).orElse("3").toString();

        //direction ：回放模式，1：正向， 0：倒放，默认正放，仅平台录像支持此
        String direction = Optional.ofNullable(param.get("direction")).orElse("1").toString();

        //rate ：播放速度，2的n次方，n取值范围[-4, 4]，仅平台录像必需此参数 24816
        String rate = Optional.ofNullable(param.get("rate")).orElse("1").toString();

        //port_type 0:HLS http-flv协议通过8060端口拉流(https为30443)，1:通过ingress40087端口拉流(https为40089) 默认值0 (只对HLS http-flv有效)
        String port_type = Optional.ofNullable(param.get("port_type")).orElse("0").toString();

        //h265_muxer_type HLS协议对于H265编码的视频的封装类型，0:fmp4封装，1:TS封装 默认0，（只对HLS协议并且当前码流是H265的时候有效）
        String h265_muxer_type = Optional.ofNullable(param.get("h265_muxer_type")).orElse("0").toString();

        // 访问IP，请求的目标IP，用于判断访问者所在的网域，默认为局域网访问
        String visit_ip = Optional.ofNullable(param.get("visit_ip")).orElse(JY_LOCALHOST_IP).toString();

        List<Map<String, Object>> mapsRtsp = new ArrayList<>();
        // 解析开始时间和结束时间参数
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime localStartDateTime = LocalDateTime.parse(param.get("startTime").toString(), formatter);
        LocalDateTime localEndDateTime = LocalDateTime.parse(param.get("endTime").toString(), formatter);

        // 转换时区为上海时间
        ZoneId shanghaiZone = ZoneId.of("GMT+8");
        ZonedDateTime shanghaiStartDateTime = localStartDateTime.atZone(shanghaiZone);
        ZonedDateTime shanghaiEndDateTime = localEndDateTime.atZone(shanghaiZone);

        long startTimestamp = shanghaiStartDateTime.toInstant().getEpochSecond();
        long endTimestamp = shanghaiEndDateTime.toInstant().getEpochSecond();

        int start_time = (int) startTimestamp;
        int end_time = (int) endTimestamp;

        Map<String, Object> resultMap = new HashMap<>();
        try {
            String url="";
            if(source_type.equals("1")){
                url = "http://" + JY_IP + ":11125/api/vms/v2/webuas/replay/stream/url?channel_code="
                        + channel_code + "&start_time=" + start_time + "&end_time=" + end_time + "&stream_mode=" + stream_mode
                        + "&source_type=" +source_type+  "&visit_ip=" + visit_ip;
            }else {
                if (stream_mode.equals("3")){
                    url = "http://" + JY_IP + ":11125/api/vms/v2/webuas/replay/stream/url?channel_code="
                            + channel_code + "&start_time=" + start_time + "&end_time=" + end_time + "&stream_mode=" + stream_mode
                            + "&source_type=" +source_type+ "&visit_ip=" + visit_ip+"&direction=" + direction + "&rate=" + rate+ "&port_type=" + port_type;
                }else {
                    url = "http://" + JY_IP + ":11125/api/vms/v2/webuas/replay/stream/url?channel_code="
                            + channel_code + "&start_time=" + start_time + "&end_time=" + end_time + "&stream_mode=" + stream_mode
                            + "&source_type=" +source_type+ "&visit_ip=" + visit_ip+"&direction=" + direction + "&rate=" + rate;
                }


            }

            // 发起HTTP请求获取回放地址
            ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
            String body = exchange.getBody();
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> responseMap = objectMapper.readValue(body, Map.class);
            String rtspValue = responseMap.get("data").toString();

            // 解析获取到的回放地址
            Map<String, String> map = Arrays.stream(rtspValue.replace("{", "").replace("}", "").split(", "))
                    .map(s -> s.split("="))
                    .collect(Collectors.toMap(s -> s[0], s -> s[1]));

            resultMap.put("rtsp", map.get("url"));
            resultMap.put("replayId", map.get("replay_id"));
            resultMap.put("rtspUrl", map.get("url"));
            resultMap.put("apeId", param.get("apeId").toString());
            mapsRtsp.add(resultMap);

        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("apeId", param.get("apeId").toString());
            resultMap.put("rtsp", "");
            mapsRtsp.add(resultMap);
        }
        return mapsRtsp;
    }

    @Override
    public Map<String, Object> getLiveStreamUrlReplayV2(Map<String, Object> param) {

        setHeaders(); // 设置请求头信息
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers); // 构造请求对象

        String channel_code = Optional.ofNullable(param.get("apeId")).orElse(null).toString();
        //source_type:录像文件源，0：平台录像，1：设备/级联录像
        String source_type = Optional.ofNullable(param.get("source_type")).orElse("1").toString();

        //stream_mode:流协议，1：RTSP，2：RTMP，3：HLS，4：HLS_SSL
        String stream_mode = Optional.ofNullable(param.get("stream_mode")).orElse(StreamProtocol.HLS.value).toString();

        //direction ：回放模式，1：正向， 0：倒放，默认正放，仅平台录像支持此
        String direction = Optional.ofNullable(param.get("direction")).orElse("1").toString();

        //rate ：播放速度，2的n次方，n取值范围[-4, 4]，仅平台录像必需此参数 24816
        String rate = Optional.ofNullable(param.get("rate")).orElse("1").toString();

        //port_type 0:HLS http-flv协议通过8060端口拉流(https为30443)，1:通过ingress40087端口拉流(https为40089) 默认值0 (只对HLS http-flv有效)
        String port_type = Optional.ofNullable(param.get("port_type")).orElse("0").toString();

        //h265_muxer_type HLS协议对于H265编码的视频的封装类型，0:fmp4封装，1:TS封装 默认0，（只对HLS协议并且当前码流是H265的时候有效）
        String h265_muxer_type = Optional.ofNullable(param.get("h265_muxer_type")).orElse("0").toString();

        // 访问IP，请求的目标IP，用于判断访问者所在的网域，默认为局域网访问
        String visit_ip = Optional.ofNullable(param.get("visit_ip")).orElse(JY_LOCALHOST_IP).toString();

        List<Map<String, Object>> mapsRtsp = new ArrayList<>();
        // 解析开始时间和结束时间参数
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime localStartDateTime = LocalDateTime.parse(param.get("startTime").toString(), formatter);
        LocalDateTime localEndDateTime = LocalDateTime.parse(param.get("endTime").toString(), formatter);

        // 转换时区为上海时间
        ZoneId shanghaiZone = ZoneId.of("GMT+8");
        ZonedDateTime shanghaiStartDateTime = localStartDateTime.atZone(shanghaiZone);
        ZonedDateTime shanghaiEndDateTime = localEndDateTime.atZone(shanghaiZone);

        long startTimestamp = shanghaiStartDateTime.toInstant().getEpochSecond();
        long endTimestamp = shanghaiEndDateTime.toInstant().getEpochSecond();

        int start_time = (int) startTimestamp;
        int end_time = (int) endTimestamp;

        Map<String, Object> resultMap = new HashMap<>();
        try {
            String url="";
            if(source_type.equals("1")){
                url = "http://" + JY_IP + ":11125/api/vms/v2/webuas/replay/stream/url?channel_code="
                        + channel_code + "&start_time=" + start_time + "&end_time=" + end_time + "&stream_mode=" + stream_mode
                        + "&source_type=" +source_type+  "&visit_ip=" + visit_ip;
            }else {
                if (stream_mode.equals("3")){
                    url = "http://" + JY_IP + ":11125/api/vms/v2/webuas/replay/stream/url?channel_code="
                            + channel_code + "&start_time=" + start_time + "&end_time=" + end_time + "&stream_mode=" + stream_mode
                            + "&source_type=" +source_type+ "&visit_ip=" + visit_ip+"&direction=" + direction + "&rate=" + rate+ "&port_type=" + port_type;
                }else {
                    url = "http://" + JY_IP + ":11125/api/vms/v2/webuas/replay/stream/url?channel_code="
                            + channel_code + "&start_time=" + start_time + "&end_time=" + end_time + "&stream_mode=" + stream_mode
                            + "&source_type=" +source_type+ "&visit_ip=" + visit_ip+"&direction=" + direction + "&rate=" + rate;
                }
            }

            // 发起HTTP请求获取回放地址
            ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
            String body = exchange.getBody();
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> responseMap = objectMapper.readValue(body, Map.class);
            String rtspValue = responseMap.get("data").toString();

            // 解析获取到的回放地址
            Map<String, String> map = Arrays.stream(rtspValue.replace("{", "").replace("}", "").split(", "))
                    .map(s -> s.split("="))
                    .collect(Collectors.toMap(s -> s[0], s -> s[1]));

            resultMap.put("replayId", map.get("replay_id"));
            resultMap.put("streamAddress", map.get("url"));
            resultMap.put("apeId", param.get("apeId").toString());
            resultMap.put("streamMode", StreamProtocol.getDescriptionByValue(Integer.parseInt(stream_mode)));


        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("apeId", param.get("apeId").toString());
            resultMap.put("rtsp", "");
            mapsRtsp.add(resultMap);
        }
        return resultMap;
    }
    @Override
    public Map<String, Object> getLiveStreamUrlReplayFinal(Map<String, Object> param) {

        setHeaders(); // 设置请求头信息
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers); // 构造请求对象

        String channel_code = Optional.ofNullable(param.get("apeId")).orElse(null).toString();
        //source_type:录像文件源，0：平台录像，1：设备/级联录像
        String source_type = Optional.ofNullable(param.get("source_type")).orElse("1").toString();

        //stream_mode:流协议，1：RTSP，2：RTMP，3：HLS，4：HLS_SSL
        String stream_mode = Optional.ofNullable(param.get("stream_mode")).orElse(StreamProtocol.HLS.value).toString();

        //direction ：回放模式，1：正向， 0：倒放，默认正放，仅平台录像支持此
        String direction = Optional.ofNullable(param.get("direction")).orElse("1").toString();

        //rate ：播放速度，2的n次方，n取值范围[-4, 4]，仅平台录像必需此参数 24816
        String rate = Optional.ofNullable(param.get("rate")).orElse("1").toString();

        //port_type 0:HLS http-flv协议通过8060端口拉流(https为30443)，1:通过ingress40087端口拉流(https为40089) 默认值0 (只对HLS http-flv有效)
        String port_type = Optional.ofNullable(param.get("port_type")).orElse("0").toString();

        //h265_muxer_type HLS协议对于H265编码的视频的封装类型，0:fmp4封装，1:TS封装 默认0，（只对HLS协议并且当前码流是H265的时候有效）
        String h265_muxer_type = Optional.ofNullable(param.get("h265_muxer_type")).orElse("0").toString();

        // 访问IP，请求的目标IP，用于判断访问者所在的网域，默认为局域网访问
        String visit_ip = Optional.ofNullable(param.get("visit_ip")).orElse(JY_LOCALHOST_IP).toString();

        List<Map<String, Object>> mapsRtsp = new ArrayList<>();
        // 解析开始时间和结束时间参数
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime localStartDateTime = LocalDateTime.parse(param.get("startTime").toString(), formatter);
        LocalDateTime localEndDateTime = LocalDateTime.parse(param.get("endTime").toString(), formatter);

        // 转换时区为上海时间
        ZoneId shanghaiZone = ZoneId.of("GMT+8");
        ZonedDateTime shanghaiStartDateTime = localStartDateTime.atZone(shanghaiZone);
        ZonedDateTime shanghaiEndDateTime = localEndDateTime.atZone(shanghaiZone);

        long startTimestamp = shanghaiStartDateTime.toInstant().getEpochSecond();
        long endTimestamp = shanghaiEndDateTime.toInstant().getEpochSecond();

        int start_time = (int) startTimestamp;
        int end_time = (int) endTimestamp;

        Map<String, Object> resultMap = new HashMap<>();
        try {
            String url="";
            if(source_type.equals("1")){
                url = "http://" + JY_IP + ":11125/api/vms/v2/webuas/replay/stream/url?channel_code="
                        + channel_code + "&start_time=" + start_time + "&end_time=" + end_time + "&stream_mode=" + stream_mode
                        + "&source_type=" +source_type+  "&visit_ip=" + visit_ip;
            }else {
                if (stream_mode.equals("3")){
                    url = "http://" + JY_IP + ":11125/api/vms/v2/webuas/replay/stream/url?channel_code="
                            + channel_code + "&start_time=" + start_time + "&end_time=" + end_time + "&stream_mode=" + stream_mode
                            + "&source_type=" +source_type+ "&visit_ip=" + visit_ip+"&direction=" + direction + "&rate=" + rate+ "&port_type=" + port_type;
                }else {
                    url = "http://" + JY_IP + ":11125/api/vms/v2/webuas/replay/stream/url?channel_code="
                            + channel_code + "&start_time=" + start_time + "&end_time=" + end_time + "&stream_mode=" + stream_mode
                            + "&source_type=" +source_type+ "&visit_ip=" + visit_ip+"&direction=" + direction + "&rate=" + rate;
                }
            }

            // 发起HTTP请求获取回放地址
            ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
            String body = exchange.getBody();
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> responseMap = objectMapper.readValue(body, Map.class);
            String rtspValue = responseMap.get("data").toString();

            // 解析获取到的回放地址
            Map<String, String> map = Arrays.stream(rtspValue.replace("{", "").replace("}", "").split(", "))
                    .map(s -> s.split("="))
                    .collect(Collectors.toMap(s -> s[0], s -> s[1]));
            String streamAddress = map.get("url");
            if (Request_Prefix!=null){
                int startIndex = streamAddress.indexOf("/vod");
                if (startIndex != -1) {
                    // 如果找到了 "/vod"，则截取从这个位置开始的所有内容
                    String rtspSubstring = streamAddress.substring(startIndex);
                    streamAddress=Request_Prefix+rtspSubstring;
                }
            }
            resultMap.put("replayId", map.get("replay_id"));
            resultMap.put("streamAddress", streamAddress);
            resultMap.put("apeId", param.get("apeId").toString());
            resultMap.put("streamMode", StreamProtocol.getDescriptionByValue(Integer.parseInt(stream_mode)));


        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("apeId", param.get("apeId").toString());
            resultMap.put("rtsp", "");
            mapsRtsp.add(resultMap);
        }
        return resultMap;
    }

    @Override
    public String getPlayRecordUrl(String channel_code, String event_time, String event_id) {
        return "http://"+JY_IP+":40087/api/vms/v2/oss-digest-vod/play-record?channel_code=" + channel_code + "&event_time=" + event_time + "&event_id=" + event_id;
    }

    @Override
    public String getIndexAndName() {
        //设置请求头信息
        setHeaders();
        // 构造请求对象
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
        String url = "http://"+JY_IP+":11125/api/bss/v1/uuv/users/privilege/device-org/tree";
        //发送get请求
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
        return exchange.getBody();
    }

    @Override
    public String addDVR(Map<String, Object> param) {
        if (!JY_SWITCH) {
            return JyDemoJsonStr.AddDVRResult;
        }
        //设置请求头信息
        setHeaders();
        //构造请求对象
        HttpEntity httpEntity = new HttpEntity(param, headers);
        String url = "http://"+JY_IP+":11125/api/bss/v1/udm/video";
        //发送请求
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
        return exchange.getBody();
    }

    @Override
    public String deleteDVR(String resource_type, String ape_ids) {
        if (!JY_SWITCH) {
            return JyDemoJsonStr.DeleteDVRResult;
        }
        //设置请求头信息
        setHeaders();
        // 构造请求对象
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
        String url = "http://"+JY_IP+":11125/api/bss/v1/udm/video?resource_type=" + resource_type + "&ape_ids=" + ape_ids;
        //发送get请求
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.DELETE, httpEntity, String.class);
        return exchange.getBody();
    }

    @Override
    public String updateDVR(Map<String, Object> param) {
        if (!JY_SWITCH) {
            return JyDemoJsonStr.UpdateDVRResult;
        }
        //设置请求头信息
        setHeaders();
        //构造请求对象
        HttpEntity httpEntity = new HttpEntity(param, headers);
        String url = "http://"+JY_IP+":11125/api/vms/v2/oms/diagnosis/video/result/record/last";
        //发送请求
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
        return exchange.getBody();
    }

    @Override
    public String selectDVRList(String resource_type, String ape_id, String ape_id_list, String name, String sub_type, String access_type, String producer, String is_online, String org_index, String include_child, String owner_aps_id, String cascaded_id, String page_size, String page_num, String ip_addr) {
        if (!JY_SWITCH) {
            return JyDemoJsonStr.DVRList;
        }
        //设置请求头信息
        setHeaders();
        // 构造请求对象
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
        StringBuilder url = new StringBuilder("http://"+JY_IP+":11125/api/bss/v1/udm/video/list?");
        if (resource_type != null)  url.append("resource_type=" + resource_type +  "&");
        if (ape_id != null) url.append("ape_id=" + ape_id +  "&");
        if (ape_id_list != null) url.append("ape_id_list=" + ape_id_list +  "&");
        if (name != null) url.append("name=" + name +  "&");
        if (sub_type != null) url.append("sub_type=" + sub_type +  "&");
        if (access_type != null) url.append("access_type=" + access_type +  "&");
        if (producer != null) url.append("producer=" + producer +  "&");
        if (is_online != null) url.append("is_online=" + ape_id +  "&");
        if (org_index != null) url.append("org_index=" + org_index +  "&");
        if (include_child != null) url.append("include_child=" + include_child +  "&");
        if (owner_aps_id != null) url.append("owner_aps_id=" + owner_aps_id +  "&");
        if (cascaded_id != null) url.append("cascaded_id=" + cascaded_id +  "&");
        if (page_size != null) url.append("page_size=" + page_size +  "&");
        if (page_num != null) url.append("page_num=" + page_num +  "&");
        if (ip_addr != null) url.append("ip_addr=" + ip_addr +  "&");
        //发送get请求
        ResponseEntity<String> exchange = restTemplate.exchange(url.toString(), HttpMethod.GET, httpEntity, String.class);
        return exchange.getBody();
    }

    @Override
    public String getVideoDiagnosisResults(String channel_name, String start_time,  Integer page_num, Integer page_size) {
        if (!JY_SWITCH) {
            return JyDemoJsonStr.videoAnalysisResult;
        }
        //设置请求头信息
        setHeaders();
        // 构造请求对象
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
        String url = "http://"+JY_IP+":11125/api/vms/v2/oms/diagnosis/video/result/record/source";
        //发送get请求
        HashMap<String, Object> map = new HashMap<>();
        map.put("channel_name", channel_name);
        map.put("start_time", start_time);
        map.put("page_num", page_num);
        map.put("page_size", page_size);
        String params = "?channel_name={channel_name}&page_num={page_num}&page_size={page_size}&start_time={start_time}";
        ResponseEntity<String> exchange = restTemplate.exchange(url + params, HttpMethod.GET, httpEntity, String.class, map);
        return exchange.getBody();
    }

    @Override
    public String getLastVideoDiagnosisResult(Map<String, Object> param) {
        if (!JY_SWITCH) {
            System.out.println("极云不可以用");
            System.out.println("极云开关没生效!!!!!!!!!!!!!!!!!!!!");
            return JyDemoJsonStr.lastVideoDiagnosisResult2;
        }
        //设置请求头信息
        setHeaders();
        //构造请求对象
        HttpEntity httpEntity = new HttpEntity(param, headers);
        String url = "http://"+JY_IP+":11125/api/vms/v2/oms/diagnosis/video/result/record/last";
        //发送请求
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
        return exchange.getBody();
    }

    @Override
    public String getLastVideoDiagnosisResultForUnitCodes(TUnitConfig tUnitConfig,Map<String, Object> param) {
        if (!JY_SWITCH) {
            System.out.println("极云不可以用");
            System.out.println("极云开关没生效!!!!!!!!!!!!!!!!!!!!");
            return JyDemoJsonStr.lastVideoDiagnosisResult2;
        }

        HttpHeaders headers = new HttpHeaders();
        //设置请求头信息
        setHeadersForUnitCodes(tUnitConfig,headers);
        // 构造请求对象
        HttpEntity<Object> httpEntity = new HttpEntity<>(param,headers);
        JY_IP=tUnitConfig.getJyIp();
        System.out.println(JY_IP);
        String url = "http://"+JY_IP+":11125/api/vms/v2/oms/diagnosis/video/result/record/last";
        //发送请求
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
        return exchange.getBody();
    }

    @Override
    public String getLastVideoDiagnosisResultByJYIP(Map<String, Object> param) {
        if (!JY_SWITCH) {
            System.out.println("极云不可以用");
            System.out.println("极云开关没生效!!!!!!!!!!!!!!!!!!!!");
            return JyDemoJsonStr.lastVideoDiagnosisResult2;
        }
        //设置请求头信息
        setHeaders();
        //构造请求对象
        HttpEntity httpEntity = new HttpEntity(param, headers);
        String url = "http://"+JY_IP+":11125/api/vms/v2/oms/diagnosis/video/result/record/last";
        //发送请求
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
        return exchange.getBody();
    }

    @Override
    public String addVideoDiagnosisScheme(Map<String, Object> param) {
        //设置请求头信息
        setHeaders();
        //构造请求对象
        HttpEntity httpEntity = new HttpEntity(param, headers);
        String url = "http://"+JY_IP+":11125/api/vms/v2/oms/diagnosis/video/scheme";
        //发送请求
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
        return exchange.getBody();
    }

    @Override
    public String updateVideoDiagnosisScheme(String schemeId, Map<String, Object> param) {
        //设置请求头信息
        setHeaders();
        //构造请求对象
        HttpEntity httpEntity = new HttpEntity(param, headers);
        String url = "http://"+JY_IP+":11125/api/vms/v2/oms/diagnosis/video/scheme/{schemeId}";
        //发送请求
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.PUT, httpEntity, String.class, schemeId);
        return exchange.getBody();
    }

    @Override
    public String selectVideoDiagnosisSchemeList(String name, Integer page_num, Integer page_size) {
        //设置请求头信息
        setHeaders();
        // 构造请求对象
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);

        StringBuilder url = new StringBuilder("http://" + JY_IP + ":11125/api/vms/v2/oms/diagnosis/video/scheme?");
        if (name != null) {
            url.append("name=" + name + "&");
        }
        if (page_num != null) {
            url.append("page_num=" + page_num + "&");
        }
        if (page_size != null) {
            url.append("page_size=" + page_size + "&");
        }

        //发送get请求
        ResponseEntity<String> exchange = restTemplate.exchange(url.toString(), HttpMethod.GET, httpEntity, String.class);

        return exchange.getBody();
    }

    @Override
    public String selectVideoDiagnosisScheme(String schemeId) {
        //设置请求头信息
        setHeaders();
        // 构造请求对象
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
        String url = "http://"+JY_IP+":11125/api/vms/v2/oms/diagnosis/video/scheme/{schemeId}";
        //发送get请求
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class, schemeId);
        return exchange.getBody();
    }

    @Override
    public String deleteVideoDiagnosisSchemes(String schemeIds) {
        //设置请求头信息
        setHeaders();
        // 构造请求对象
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
        String url = "http://"+JY_IP+":11125/api/vms/v2/oms/diagnosis/video/scheme?ids=" + schemeIds;
        //发送get请求
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.DELETE, httpEntity, String.class);
        return exchange.getBody();
    }

    @Override
    public String addVideoDiagnosisPlan(Map<String, Object> param) {
        if (!JY_SWITCH) {
            return " ";
        }
        //设置请求头信息
        setHeaders();
        //构造请求对象
        HttpEntity httpEntity = new HttpEntity(param, headers);
        String url = "http://"+JY_IP+":11125/api/vms/v2/oms/diagnosis/video/plan";
        //发送请求
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
        return exchange.getBody();
    }

    @Override
    public String updateVideoDiagnosisPlan(String planId, Map<String, Object> param) {
        if (!JY_SWITCH) {
            return " ";
        }
        //设置请求头信息
        setHeaders();
        //构造请求对象
        HttpEntity httpEntity = new HttpEntity(param, headers);
        String url = "http://"+JY_IP+":11125/api/vms/v2/oms/diagnosis/video/plan/{planId}";
        //发送请求
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.PUT, httpEntity, String.class, planId);
        return exchange.getBody();
    }

    @Override
    public String selectVideoDiagnosisPlanList(String name, Integer page_num, Integer page_size) {
        if (!JY_SWITCH) {
            return " ";
        }
        //设置请求头信息
        setHeaders();
        // 构造请求对象
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);

        StringBuilder url = new StringBuilder("http://" + JY_IP + ":11125/api/vms/v2/oms/diagnosis/video/plan?");
        if (name != null) {
            url.append("name=" + name + "&");
        }
        if (page_num != null) {
            url.append("page_num=" + page_num + "&");
        }
        if (page_size != null) {
            url.append("page_size=" + page_size + "&");
        }

        //发送get请求
        ResponseEntity<String> exchange = restTemplate.exchange(url.toString(), HttpMethod.GET, httpEntity, String.class);

        return exchange.getBody();
    }

    @Override
    public String selectVideoDiagnosisPlan(String planId) {
        if (!JY_SWITCH) {
            return " ";
        }
        //设置请求头信息
        setHeaders();
        // 构造请求对象
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
        String url = "http://"+JY_IP+":11125/api/vms/v2/oms/diagnosis/video/plan/{plan}";
        //发送get请求
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class, planId);
        return exchange.getBody();
    }

    @Override
    public String deleteVideoDiagnosisPlans(String planIds) {
        if (!JY_SWITCH) {
            return " ";
        }
        //设置请求头信息
        setHeaders();
        // 构造请求对象
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
        String url = "http://"+JY_IP+":11125/api/vms/v2/oms/diagnosis/video/plan?ids=" + planIds;
        //发送get请求
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.DELETE, httpEntity, String.class);
        return exchange.getBody();
    }

    @Override
    public String updatePlanStatus(String ids, Integer status) {
        if (!JY_SWITCH) {
            return " ";
        }
        //设置请求头信息
        setHeaders();
        // 构造请求对象
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
        String url = "http://"+JY_IP+":11125/api/vms/v2/oms/diagnosis/video/plan/status/update?ids="+ids+"&status="+status;
        //发送get请求
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.PUT, httpEntity, String.class);
        return exchange.getBody();
    }



    @Override
    public String getInstalledAlgorithms() {
        if (!JY_SWITCH) {
            return JyDemoJsonStr.installedAlgos;
        }
        //设置请求头信息
        setHeaders();
        // 构造请求对象
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
        String url = "http://"+JY_IP+":11125/api/vias/v2/awh/deployment/installed-algos?page_num=1&page_size=100";
        //发送get请求
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
        return exchange.getBody();
//        return installedAlgoStr;
    }

    @Override
    public String getInstalledAlgorithmsForUnitCodes(TUnitConfig tUnitConfig) {
        if (!JY_SWITCH) {
            return JyDemoJsonStr.installedAlgos;
        }
        HttpHeaders headers = new HttpHeaders();
        //设置请求头信息
        setHeadersForUnitCodes(tUnitConfig,headers);
        // 构造请求对象
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
        JY_IP=tUnitConfig.getJyIp();
        String url = "http://"+JY_IP+":11125/api/vias/v2/awh/deployment/installed-algos?page_num=1&page_size=100";
        //发送get请求
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
        return exchange.getBody();
//        return installedAlgoStr;
    }
    @Override
    public String getVideoAnalysisTasks() {
        if (!JY_SWITCH) {
            return JyDemoJsonStr.videoAnalysisTask;
        }
        //设置请求头信息
        setHeaders();
        // 构造请求对象
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
        String url = "http://"+JY_IP+":11125/api/vias/v2/video-analysis/tasks?page_num=1&page_size=100";
        //发送get请求
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
        return exchange.getBody();
//        return  videoAnalysisTaskStr;
    }

    @Override
    public String getVideoAnalysisTasksForUnitCodes(TUnitConfig tUnitConfig) {
        if (!JY_SWITCH) {
            return JyDemoJsonStr.videoAnalysisTask;
        }
        HttpHeaders headers = new HttpHeaders();
        //设置请求头信息
        setHeadersForUnitCodes(tUnitConfig,headers);
        // 构造请求对象
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
        JY_IP=tUnitConfig.getJyIp();
        String url = "http://"+JY_IP+":11125/api/vias/v2/video-analysis/tasks?page_num=1&page_size=100";
        //发送get请求
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
        return exchange.getBody();
//        return  videoAnalysisTaskStr;
    }

    @Override
    public String countOnlineRate(String pageSize, String pageNum) {

        //设置请求头信息
        setHeaders();
        // 构造请求对象
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
        if (pageSize == null || pageNum == null) {
            pageSize = "9999";
            pageNum = "1";
        }
        String url = "http://"+JY_IP+":11125/api/vms/v1/oms/statistics/channel/online" + "?page_size="+pageSize+"&page_num="+pageNum;
        //发送get请求
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
        return exchange.getBody();
    }

    @Override
    public String countComplianceRatio(String pageSize, String pageNum, String queryDate) {
        //设置请求头信息
        setHeaders();
        // 构造请求对象
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
        String url = "http://"+JY_IP+":11125/api/vms/v1/oms/statistics/channel/diagnosis";
        String params = "?page_size=" + pageSize + "&page_num=" + pageNum + "&query_date=" + queryDate;
        String realUrl = url;
        if (pageSize != null && pageNum != null && queryDate != null) {
            realUrl += params;
        }
        //发送get请求
        ResponseEntity<String> exchange = restTemplate.exchange(realUrl, HttpMethod.GET, httpEntity, String.class);
        return exchange.getBody();
    }


    @Override
    public AjaxResult batchAddDiagnosisPlan(DiagnosisPlanRequestBody requestBody) {
        String startTimeDate = requestBody.getStartTime();
        String endTimeDate = requestBody.getEndTime();

        // 定义日期时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // 将String转换为LocalDateTime对象
        LocalDateTime startTime = LocalDateTime.parse(startTimeDate, formatter);
        LocalDateTime endTime= LocalDateTime.parse(endTimeDate, formatter);

        Integer plusMinutes = requestBody.getPlusMinutes();
        String schemeName = requestBody.getSchemeName();
        String[] monitorIdArr = requestBody.getMonitorIdArr();
        String coalMineName = requestBody.getCoalMineName();

        while (startTime.compareTo(endTime) < 0) {
            DateTimeFormatter nameFormatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
            DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            //根据schemeName查询id
            String schemeListJsonStr = selectVideoDiagnosisSchemeList(schemeName, 1, 1);
            int schemeId = getSchemeIdOfFirstScheme(schemeListJsonStr);
            HashMap<String, Object> map = new HashMap<>();
            map.put("name", coalMineName + "预案_" + startTime.format(nameFormatter));
            map.put("over_time", 5);
            map.put("type", 1);
            map.put("start_time", startTime.format(dateFormatter));
            map.put("channels", monitorIdArr);
            map.put("status", 1);
            map.put("scheme_id", schemeId);
            addVideoDiagnosisPlan(map);
            startTime  = startTime.plusMinutes(plusMinutes);
        }
        return AjaxResult.success();
    }

    @Override
    public Map<String, Object> getReplayStreamUrl(String channel_code, String start_time, String end_time) {


        //设置请求头信息
        setHeaders();
        // 构造请求对象
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);

        System.out.println(headers.get("Authorization"));
        String url = "http://"+JY_IP+":11125/api/vms/v2/webuas/record/stream/start";
        String params = "?channel_code=" + channel_code + "&start_time=" + GenericMethods.convertTimestamp(start_time)
                + "&end_time=" + GenericMethods.convertTimestamp(end_time)+ "&source_type=1" +"&muxer_type=1";
        String realUrl = url;
        realUrl += params;
        //发送get请求
        ResponseEntity<String> exchange = restTemplate.exchange(realUrl, HttpMethod.GET, httpEntity, String.class);
        String body = exchange.getBody();
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> responseMap = objectMapper.readValue(body, Map.class);
            Map<String, String> dataMap = (Map<String,String>)responseMap.get("data");
            return responseMap;
        }catch (Exception e){
            HashMap<String, Object> ErrorMap = new HashMap<>();
            ErrorMap.put("code",500);
            ErrorMap.put("message","请求失败");
            return ErrorMap;
        }



        //发送get请求
//        ResponseEntity<String> exchange = restTemplate.exchange(realUrl, HttpMethod.GET, httpEntity, String.class);
    }

    @Override
    public Map<String, Object> getReplayStreamUrlv2(String channel_code, String start_time, String end_time) {

        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization",(String) servletContext.getAttribute("access_token"));
        headers.set("User", user);
        headers.set("Cookie", cookie);
        headers.set("Content-Type", contentType);
        // 构造请求对象
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
        String url = "http://"+JY_IP+":11125/api/vms/v2/webuas/record/stream/start";
        String params = "?channel_code=" + channel_code + "&start_time=" + GenericMethods.convertTimestamp(start_time)
                + "&end_time=" + GenericMethods.convertTimestamp(end_time)+ "&source_type=1" +"&muxer_type=1";
        String realUrl = url;
        realUrl += params;
        //发送get请求
        ResponseEntity<String> exchange = restTemplate.exchange(realUrl, HttpMethod.GET, httpEntity, String.class);
        String body = exchange.getBody();
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> responseMap = objectMapper.readValue(body, Map.class);
            Map<String, String> dataMap = (Map<String,String>)responseMap.get("data");
            return responseMap;
        }catch (Exception e){
            HashMap<String, Object> ErrorMap = new HashMap<>();
            ErrorMap.put("code",500);
            ErrorMap.put("message","请求失败");
            return ErrorMap;
        }



        //发送get请求
//        ResponseEntity<String> exchange = restTemplate.exchange(realUrl, HttpMethod.GET, httpEntity, String.class);
    }

    @Override
    public Map<String, Object> getRecordStreamDownload(String channel_code, String start_time, String end_time,String outputFile) {
        System.out.println("getRecordStreamDownload:" + LocalDateTime.now());

        Map<String, Object> replayStreamUrl = getReplayStreamUrl(channel_code, start_time, end_time);
        Map<String,String> data = (Map<String,String>)replayStreamUrl.get("data");
        String url = data.get("url");
        String query_url = data.get("query_url");

        //设置请求头信息
        setHeaders();
        // 构造请求对象
        headers.set("Accept", "video/*");
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
        int retries=0;
        while (retries < 100) {
            ResponseEntity<byte[]> response = restTemplate.exchange(
                    url,
                    HttpMethod.GET,
                    httpEntity,
                    byte[].class);

            HttpStatus statusCode = response.getStatusCode();

            if (statusCode.is2xxSuccessful()) {
                if (statusCode.value() == 200) {
                    byte[] videoData = response.getBody();
                    AjaxResult ajaxResult = GenericMethods.saveToFile(videoData, outputFile);


                    System.out.println("File saved successfully.");
                    break; // 成功后退出循环
                } else if (statusCode.value() == 202) {
                    System.out.println("Received 202, waiting and retrying... Retry count: " + retries);
                    try {
                        // 等待5秒
                        TimeUnit.SECONDS.sleep(10);
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        System.err.println("Thread was interrupted: " + e.getMessage());
                    }
                } else {
                    System.err.println("Unexpected status code: " + statusCode);
                    break; // 非预期的状态码，退出循环
                }
            } else {
                System.err.println("Unexpected status code: " + statusCode);
                break; // 非2xx的状态码，退出循环
            }
            retries++;
        }
        return null;
    }

    private Integer getSchemeIdOfFirstScheme(String schemeListJsonStr) {
        JSONArray jsonArray = JSONObject.parseObject(schemeListJsonStr).getJSONObject("data").getJSONArray("data");
        return jsonArray.getJSONObject(0).getIntValue("id");
    }

    public static List<String> extractSegments(String input) {
        List<String> segments = new ArrayList<>();
        Pattern pattern = Pattern.compile("\\b.+?\\.mp4\\b");
        Matcher matcher = pattern.matcher(input);
        while (matcher.find()) {
            segments.add(matcher.group());
        }
        List<String> modifiedSegments = new ArrayList<>();
        for (String segment : segments) {
            int startIndex = segment.indexOf("desc") + 4; // Adjust start index to after "desc"
            int endIndex = segment.indexOf(".mp4") + 4; // Include .mp4 in the substring
            if (startIndex >= 4 && endIndex != -1) { // Check if "desc" was found and ".mp4" exists
                String modifiedSegment = segment.substring(startIndex, endIndex);
                modifiedSegments.add(modifiedSegment);
            }
        }
        return modifiedSegments;
    }
    public static String extractHLS(String input) {
        String hls = "";

        // 使用正则表达式提取内容
        Pattern pattern = Pattern.compile("desc([^/]+)"); // 匹配以 "desc" 开头，到下一个 "/" 结束的内容
        Matcher matcher = pattern.matcher(input);
        if (matcher.find()) {
            hls = matcher.group(1); // 使用 group(1) 获取匹配的内容，不包括 "desc"
        }

        return hls;
    }

    public static JSONObject parse(String input) {
        JSONObject result = new JSONObject();

        // 解析版本号
        Pattern versionPattern = Pattern.compile("#EXT-X-VERSION:(\\d+)");
        Matcher versionMatcher = versionPattern.matcher(input);
        if (versionMatcher.find()) {
            result.put("version", versionMatcher.group(1));
        }

        // 解析地图URI
        Pattern mapPattern = Pattern.compile("#EXT-X-MAP:URI=\\\"(.*?)\\\"");
        Matcher mapMatcher = mapPattern.matcher(input);
        if (mapMatcher.find()) {
            result.put("map_uri", mapMatcher.group(1));
        }

        // 解析媒体序列
        Pattern sequencePattern = Pattern.compile("#EXT-X-MEDIA-SEQUENCE:(\\d+)");
        Matcher sequenceMatcher = sequencePattern.matcher(input);
        if (sequenceMatcher.find()) {
            result.put("media_sequence", sequenceMatcher.group(1));
        }

        // 解析目标持续时间
        Pattern durationPattern = Pattern.compile("#EXT-X-TARGETDURATION:(\\d+)");
        Matcher durationMatcher = durationPattern.matcher(input);
        if (durationMatcher.find()) {
            result.put("target_duration", durationMatcher.group(1));
        }

        // 解析媒体片段
        JSONArray segmentsArray = new JSONArray();
        Pattern segmentPattern = Pattern.compile("#EXTINF:(\\d+\\.\\d+),.*?/(.*?\\.mp4)");
        Matcher segmentMatcher = segmentPattern.matcher(input);
        while (segmentMatcher.find()) {
            String duration = segmentMatcher.group(1);
            String uri = segmentMatcher.group(2);

            // 截取URI中以"16"开头和".mp4"结尾的部分
            int startIndex = uri.indexOf("16");
            int endIndex = uri.indexOf(".mp4");
            if (startIndex != -1 && endIndex != -1 && endIndex > startIndex) {
                uri = uri.substring(startIndex, endIndex + 4);
            }

            JSONObject segmentObj = new JSONObject();
            segmentObj.put("duration", duration);
            segmentObj.put("uri", uri); // 使用截取的部分作为URI
//            segmentsArray.put(segmentObj);
        }
        result.put("segments", segmentsArray);

        return result;
    }

    private String buildLiveUrl(String channel_code, String stream_type, String stream_mode, String keep_alive, String visit_ip,String port_type,String h265_muxer_type) {
        return "http://" + JY_IP + ":11125/api/vms/v2/webuas/live/stream/url?channel_code=" +
                channel_code + "&stream_type=" + stream_type + "&stream_mode=" + stream_mode +
                "&keep_alive=" + keep_alive + "&visit_ip=" + visit_ip+ "&port_type=" + port_type+ "&h265_muxer_type=" + h265_muxer_type;
    }
}
